package tcp

import (
	"bytes"
	"ce-cloud/pkg/log"
	"encoding/binary"
	"net"
	"time"
)

func Start() {
	defer func() {
		if r := recover(); r != nil {
			log.Fatal("recover:", r)
		}
	}()
	conn, err := net.Dial("tcp", "127.0.0.1:8999")
	if err != nil {
		log.Error("err:", err)
		return
	}
	for {
		data := []byte("hello")
		dataBuff := bytes.NewBuffer([]byte{})
		msg := struct {
			MsgID   uint32
			MsgLen  uint32
			MsgData []byte
		}{MsgID: 1, MsgLen: uint32(len(data)), MsgData: []byte(data)}
		//写msgID
		if err := binary.Write(dataBuff, binary.BigEndian, msg.MsgID); err != nil {
			return
		}

		//写dataLen
		if err := binary.Write(dataBuff, binary.BigEndian, msg.MsgLen); err != nil {
			return
		}

		//写data数据
		if err := binary.Write(dataBuff, binary.BigEndian, msg.MsgData); err != nil {
			return
		}
		log.Infof("write:%+v", string(dataBuff.Bytes()))
		_, err = conn.Write(dataBuff.Bytes())
		if err != nil {
			return
		}
		time.Sleep(time.Second * 1)
	}
}
